// The employee's connection handler. Can connect and disconnect from the server when necessary.

#include "../include/ConnectionHandler.h"

using Poco::Net::StreamSocket;
using Poco::Net::SocketStream;
using Poco::Net::SocketAddress;
using Poco::Exception;


// Class constructor. Receives the server name and port, and builds a stream socket and a socket stream accordingly.
ConnectionHandler::ConnectionHandler(std::string host, short port):  sa_(host, port), sock_(), stream_(sock_), port_(port), host_(host){
}

// Class destructor. Closes down the stream socket.
ConnectionHandler::~ConnectionHandler(void){
	try{
		sock_.shutdown();
	} catch (...) {
		cout << "closing failed: connection already closed" << endl;
	}
}

// Connects to a remote machine
// Returns false if it was unable to properly connect.
bool ConnectionHandler::connect() {
	// Initiate blocking connection with server.
	cout << "Starting to connect to "
	<< sa_.host().toString() << ":" << sa_.port() << endl;
	try {
		sock_.connect(sa_);
	}
	catch (Poco::Exception error) {
		cout << "Connection failed (Error: " << error.displayText() << ')' << endl;
		return false;
	}
	return true;
}

